var pageContext = new PageContext(settings||{});
pageContext.formInit = function(layero){
	
}
pageContext.importData = function(me){
	if(step.imported){
		alert("该文件已经成功导入，不能重复导入！");
		return false;
	}
	step.step3 = false;
	$(me).attr("disabled",true);
    var searchParames = '' ; 
    var from = $("#step2Form");
    searchParames = from.formSerializeNotBlank();
    searchParames+="&url="+myDropzone.data.responseText.data.success[0].url;
	$.get(window.global.ctx+"/data/table/data/import",searchParames,function(result){
		$(me).attr("disabled",false);
		if(result&& result.status==200){
			step.step3 = true;
		  	step.imported = true;
			$("#result").text("导入成功！");
			wizard.wizard('next');
		}else{
			resetFlow();
			alert(result.msg);
		}
	});
    return false;
}
function resetFlow(){
	$(".steps li:first").click();
	var from = $("#step2Form");
	from.resetForm();
	var select = $(".execlfields");
	select.empty();
	myDropzone.removeAllFiles(true);
  	myDropzone.data = {};
  	step.step1 = false;
  	step.step2 = false;
  	step.step3 = false;
  	step.step4 = false;
  	step.imported = false;
}
var step = {};
var wizard = null;
var myDropzone = null;
jQuery(function($) {
	 pageContext.init();
	 $('#previews').resize(function(){
		 parent.iframeTab.iframeResize();
	 });
	$("#step2Form").validationEngine('attach', {promptPosition : "topLeft", autoPositionUpdate : true});
	var $validation = false;
	wizard = $('#fuelux-wizard-container')
	.ace_wizard({
		//step: 2 //optional argument. wizard will jump to step "2" at first
		//buttons: '.wizard-actions:eq(0)'
	})
	.on('actionclicked.fu.wizard' , function(e, info){
		console.log()
		console.log(info)
		$(".btn-next").attr("disabled",true);
		if(info.step == 1 && info.direction=="next") {
			var list = myDropzone.getFilesWithStatus(Dropzone.SUCCESS);
			if(!list || list.length<=0){
				 alert("请选择及上传需要导入的文件！");
				 $(".btn-next").attr("disabled",false);
				 step.step1 = false;
	        	 return false;
			}else{
				if(!myDropzone.data.head){
					var data = {url:myDropzone.data.responseText.data.success[0].url};
					$.get(window.global.ctx+"/data/table/data/fileFields",data,function(result){
						if(result&& result.status==200){
							wizard.wizard('next');
							myDropzone.data.head=result.data;
							$(".btn-next").attr("disabled",false);
							var map = result.data;
							var select = $(".execlfields");
							select.empty();
							select.append("<option value=''>--请选择列--</option>");
							for(key in map){
								var index = map[key];
								select.append("<option value='"+index+"'>"+key+"</option>");
							}
							step.step1 = true;
							return true;
						}else{
							alert(result.msg);
							$(".btn-next").attr("disabled",false);
							step.step1 = false;
							return false;
						}
					});
					step.step1 = false;
					 $(".btn-next").attr("disabled",false);
					return false;
				}else{
					step.step1 = true;
					 $(".btn-next").attr("disabled",false);
					return true;
				}
			}
		}else if(step.step1 && info.step == 2 && info.direction=="next") {
			 var from = $("#step2Form");
			 var searchParames = '' ; 
	         searchParames = from.formSerializeNotBlank();
	         console.log(searchParames)
			 if(from.validationEngine("validate")){
				 $(".btn-next").attr("disabled",false); 
				 step.step2 = true;
				 return true;
			 }else{
				 $(".btn-next").attr("disabled",false);
				 step.step2 = false;
				 return false;
			 }
		}else if(step.step2 && info.step == 3 && info.direction=="next") {
			 $(".btn-next").attr("disabled",false); 
			 if(step.step3){
				 return true;
			 }else{
				 alert("请点击导入，待导入完成后，再点击下一步！");
				 return false;
			 }
		}
		$(".btn-next").attr("disabled",false);
		return true;
	})
	.on('finished.fu.wizard', function(e,info) {
		bootbox.dialog({
			message: "您的导入数据流程已完成！", 
			buttons: {
				"success" : {
					"label" : "OK",
					"className" : "btn-sm btn-primary"
				}
			}
		});
		resetFlow();
	}).on('stepclick.fu.wizard', function(e,info){
		console.log("click")
		console.log(e)
		console.log(info)
		//e.preventDefault();//this will prevent clicking and selecting steps
	}).on('changed.fu.wizard', function(e,info){
		console.log()
		console.log("changed"+":")
		console.log(e)
		console.log(info)
		//e.preventDefault();//this will prevent clicking and selecting steps
	});
//	previous	Moves to the previous step
//	next	Moves to the next step
//	selectedItem	Returns the current step index
	$('#modal-wizard-container').ace_wizard();
	$('#modal-ccc .wizard-actions .btn[data-dismiss=modal]').removeAttr('disabled');
	 
	var url = window.global.ctx+"/sys/file/upload"; 
	
	 // Get the template HTML and remove it from the doument
    var previewNode = document.querySelector("#template");
    previewNode.id = "";
    previewNode.style.display="";
    var previewTemplate = previewNode.parentNode.innerHTML;
    previewNode.parentNode.removeChild(previewNode);
    
	myDropzone = new Dropzone(document.body, { // Make the whole body a dropzone
	        url: url, // Set the url
	        thumbnailWidth: 80,
	        thumbnailHeight: 80,
	        parallelUploads: 20,
	        maxFilesize:50,
	        maxFiles:1,
	        dictInvalidFileType: "不支持该类型的文件。",
	        dictCancelUploadConfirmation: "确定取消上传该文件?",
	        dictResponseError:"服务器返回{{statusCode}}。",
	        dictRemoveFileConfirmation:"确定删除该文件？",
	        dictMaxFilesExceeded: "您最多只能上传{{maxFiles}}个文件！",
	        dictResponseError: '文件上传失败!',
	        dictInvalidFileType: "你不能上传该类型文件,文件类型只能是*.xls,*.xlsx。",
	        dictFallbackMessage:"浏览器不受支持",
	        dictFileTooBig:"文件过大({{filesize}}MiB),上传文件最大支持{{maxFilesize}}MiB.",
	        acceptedFiles:".csv",
	        previewTemplate: previewTemplate,
	        autoQueue: false, // Make sure the files aren't queued until manually added
	        previewsContainer: "#previews", // Define the container to display the previews
	        clickable: ".fileinput-button" // Define the element that should be used as click trigger to select files.
	      });
	  	  myDropzone.data = {};
	      myDropzone.on("addedfile", function(file) {
	    	  $("#previews").resize();
	        // Hookup the start button
	        file.previewElement.querySelector(".start").onclick = function() { myDropzone.enqueueFile(file); };
	      });

	      // Update the total progress bar
	      myDropzone.on("totaluploadprogress", function(progress) {
	        document.querySelector("#total-progress .progress-bar").style.width = progress + "%";
	      });

	      myDropzone.on("sending", function(file) {
	        // Show the total progress bar when upload starts
	        document.querySelector("#total-progress").style.opacity = "1";
	        // And disable the start button
	        file.previewElement.querySelector(".start").setAttribute("disabled", "disabled");
	      });

	      // Hide the total progress bar when nothing's uploading anymore
	      myDropzone.on("queuecomplete", function(progress) {
	        document.querySelector("#total-progress").style.opacity = "0";
	      });
	      myDropzone.on("success", function(file, responseText, e) {
	    	  console.log("success:")
	    	  console.log(file)
	    	  console.log(responseText)
	    	  myDropzone.data.responseText = responseText;
	      });
	      myDropzone.on("canceled", function(file) {
	    	  console.log("canceled:")
	    	  console.log(file)
		  });
	      myDropzone.on("removedfile", function(file) {
	    	  console.log("removedfile:")
	    	  console.log(file);
	    	  $.get(myDropzone.data.responseText.data.success[0].deleteUrl,null,function(result){
	    		  if(result&& result.status==200){
	    		  }
	    	  });
	    	  myDropzone.data = {};
	    	  step.step1 = false;
	    	  step.step2 = false;
	    	  step.step3 = false;
	    	  step.step4 = false;
	      });
	      
	      // Setup the buttons for all transfers
	      // The "add files" button doesn't need to be setup because the config
	      // `clickable` has already been specified.
//	      document.querySelector("#actions .start").onclick = function() {
//	      };
//	      document.querySelector("#actions .cancel").onclick = function() {
//	      };
//	      document.querySelector("#actions .delete").onclick = function() {
//	         myDropzone.removeAllFiles(true);
//	      };
//	      $("#actions .start").on(function(){
//	    	  console.log("start:")
//	    	  myDropzone.enqueueFiles(myDropzone.getFilesWithStatus(Dropzone.ADDED));
//	      });
//	      $("#actions .cancel").on(function(){
//	    	  console.log("cancel:")
//	    	  myDropzone.cancelUpload(myDropzone.getFilesWithStatus(Dropzone.ADDED));
//	      });
//	      $("#actions .delete").on(function(){
//	    	  console.log("delete:")
//	    	  myDropzone.removeAllFiles(true);
//	      });
});

